package com.lilicould.service;

import com.google.gson.Gson;
import com.lilicould.dao.ScheduleDao;
import com.lilicould.entity.ScheduleDetails;
import com.lilicould.entity.Schedules;
import com.lilicould.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class ScheduleService {

    // 获取教师编号对应的课程安排
    public String getSchedulesByTeacherUserNo(String userNo) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            ScheduleDao scheduleDao = sqlSession.getMapper(ScheduleDao.class);
            // 获取教师编号对应的课程安排
            List<ScheduleDetails> scheduleDetails = scheduleDao.getSchedulesByTeacherUserNo(userNo);
            if (scheduleDetails != null) {
                // 获取成功
                return new Gson().toJson(scheduleDetails);
            } else {
                return null;
            }
        }catch (Exception e) {
            return null;
        }
    }

    public String getAllSchedules() {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            ScheduleDao scheduleDao = sqlSession.getMapper(ScheduleDao.class);
            // 获取所有课程安排
            List<ScheduleDetails> scheduleDetails = scheduleDao.getAllSchedules();
            if (scheduleDetails != null) {
                // 返回所有课程安排,转换为JSON格式
                return new Gson().toJson(scheduleDetails);
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }

    public String addSchedule(Schedules schedule) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            ScheduleDao scheduleDao = sqlSession.getMapper(ScheduleDao.class);
            // 添加课程安排
            int result = scheduleDao.addSchedule(schedule);
            if (result > 0) {
                // 添加成功
                sqlSession.commit();
                return null;
            } else {
                return new Gson().toJson("数据库返回结果不大于0");
            }
        } catch (Exception e) {
            // 返回错误信息
            return new Gson().toJson(e.getMessage());
        }
    }

    public String deleteSchedule(int id) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
            // 获取映射器对象
            ScheduleDao scheduleDao = sqlSession.getMapper(ScheduleDao.class);

            // 删除课程安排并且返回删除结果
            int result = scheduleDao.deleteSchedule(id);
            if (result > 0) {
                // 删除成功
                sqlSession.commit();
                return null;
            }else {
                return new Gson().toJson("数据库返回结果小于0");
            }
        } catch (Exception e) {
            // 捕获异常并返回错误信息
            return new Gson().toJson(e.getMessage());
        }
    }
}
